package com.atguigu.Des;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 * @author : wushikai
 * <p>
 * date : 2021-04-22
 */
public class MyAesUtil {


    /**
     *  因为使用了填充模式为NoPadding，输入的需要加密的报文长度必须是16(128bit)的倍数
     */
    public static String encryptByAes(String input, String key) throws Exception {
        //这里指定了算法为AES_128，工作模式为EBC，填充模式为NoPadding
        Cipher cipher = Cipher.getInstance("AES_128/ECB/NoPadding");
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        //因为AES要求密钥的长度为128，我们需要固定的密码，因此随机源的种子需要设置为我们的密码数组
        keyGenerator.init(128, new SecureRandom(key.getBytes()));
        SecretKey secretKey = keyGenerator.generateKey();
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
        //基于加密模式和密钥初始化Cipher
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        //单部分加密结束，重置Cipher
        byte[] bytes = cipher.doFinal(input.getBytes());
        //加密后的密文由二进制序列转化为十六进制序列，依赖apache-codec包
        return Hex.encodeHexString(bytes);
    }


    public static String decryptByAes(String content, String key) throws Exception {
        //这里要把十六进制的序列转化回二进制的序列，依赖apache-codec包
        byte[] bytes = Hex.decodeHex(content.toCharArray());
        //这里指定了算法为AES_128，工作模式为EBC，填充模式为NoPadding
        Cipher cipher = Cipher.getInstance("AES_128/ECB/NoPadding");
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        //因为AES要求密钥的长度为128，我们需要固定的密码，因此随机源的种子需要设置为我们的密码数组
        keyGenerator.init(128, new SecureRandom(key.getBytes()));
        SecretKey secretKey = keyGenerator.generateKey();
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
        //基于解密模式和密钥初始化Cipher
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        //单部分加密结束，重置Cipher
        byte[] result = cipher.doFinal(bytes);
        return new String(result);
    }

    public static void test() {


        String key = "1234567812345678";
        String input = "aa艹艹艹艹aa";   //javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes


        try {
            String encryptionStr = encryptByAes(input, key);
            System.out.println("encryptionStr = " + encryptionStr);

            String s = decryptByAes(encryptionStr, key);
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    public static void main(String[] args) {
        test();


    }


}
